plugins {
    id "java"
    // As Wasmer is a package, we need tools to build the JARs and so
    id "java-library"
    id "com.jfrog.bintray" version "1.8.5"
}

allprojects {
    group "org.wasmer"
    version "0.3.0"
}

// This is needed for the Java plugin to make sure
// the generated class files are compatible with
// old versions of Java.
sourceCompatibility = 1.8
targetCompatibility = 1.8

sourceSets {
    main {
        java {
            srcDirs = ["src/java"]
        }
        resources {
            srcDirs = ["$buildDir/toArtifact"]
        }
    }
    test {
        java {
            srcDirs = ["tests"]
        }
        resources {
            srcDirs = ["tests/resources"]
        }
    }
}

javadoc {
    options.links "https://docs.oracle.com/javase/8/docs/api/"
    // TODO: change when https://github.com/gradle/gradle/issues/2354 is fixed
    options.addStringOption "Xdoclint:all", "-Xdoclint:-missing"
}

repositories {
    jcenter()
    google()
    maven {
        url "https://plugins.gradle.org/m2/"
    }
}

dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter-api:5.4.2")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.4.2")
}

test {
    useJUnitPlatform()
}

jar {
    manifest {
        attributes("Implementation-Title": project.name,
                   "Implementation-Version": project.version)
    }

    // The JAR name is defined as
    // `${baseName}-${appendix}-${version}-${classifier}.${extension}`.
    archiveAppendix = inferWasmerJarAppendix()
}

String inferWasmerJarAppendix() {
    def nativePlatform = new org.gradle.nativeplatform.platform.internal.DefaultNativePlatform("current")
    def arch = nativePlatform.architecture
    def os = nativePlatform.operatingSystem

    def arch_name

    switch (arch.getName()) {
        case ["x86_64", "x64", "x86-64"]:
            arch_name = "amd64"
            break;

        case ["aarch64", "arm-v8"]:
            arch_name = "arm64"
            break;

        default:
            throw new RuntimeException("Architecture " + arch.getName() + " is not supported.")
    }

    def os_name

    if (os.isMacOsX()) {
        os_name = "darwin"
    } else if (os.isLinux()) {
        os_name = "linux"
    } else if (os.isWindows()) {
        os_name = "windows"
    } else {
        throw new RuntimeException("Platform " + os.getName() + " is not supported.")
    }

    return arch_name + "-" + os_name
}

task generateJniHeaders(type: JavaCompile) {
    description "Generate the JNI header files (in `include/`)."

    classpath = sourceSets.main.compileClasspath
    destinationDir file("include")
    source = sourceSets.main.java
    options.compilerArgs += [
        "-h", file("include"),
    ]
    options.verbose = true
}

task buildRust(type: Exec) {
    dependsOn generateJniHeaders

    description "Build the Rust project."

    commandLine "make", "build-rust"
}

task copyAllArtifacts(type: Copy) {
    dependsOn buildRust

    description "Copy build artifacts to the `build/` directory."

    from "artifacts"
    include "**/*"
    into "$buildDir/toArtifact/org/wasmer/native/"
}

tasks.withType(Test) {
    // We add the path, so the Java Tests can find the
    // shared object file
    systemProperty "java.library.path", "target/current/"

    testLogging {
        outputs.upToDateWhen { false }

        // Don"t capture the standard output.
        showStandardStreams = true
    }
}

jar.doLast() {
    // Display specific “action outputs” for Github Actions.
    def jar_name = project.archivesBaseName + "-" + inferWasmerJarAppendix() + "-" + project.version + ".jar"
    println(jar_name)
    println("::set-output name=path::./build/libs/" + jar_name)
    println("::set-output name=name::" + jar_name)
}

jar.outputs.upToDateWhen { false }

// We build the integration before running any test
compileTestJava.dependsOn buildRust
processResources.dependsOn copyAllArtifacts

// Publishing on bintray.
task uploadToBintray {
    dependsOn bintrayUpload

    apply plugin: "maven"
    apply plugin: "maven-publish"

    /// First, set up a POM configuration.
    def pomConfig = {
        name "wasmer-jni"
        packaging "jar"
        description "Wasmer JNI is a library to execute WebAssembly binaries"
        url "https://wasmer.io"
        scm {
            connection "scm:git:git@github.com:wasmerio/wasmer-java.git"
            developerConnection "scm:git:git@github.com:wasmerio/wasmer-java.git"
            url "git@github.com:wasmerio/wasmer-java.git"
        }
        licenses {
            license {
                name "MIT License"
                url "https://opensource.org/licenses/MIT"
            }
        }
        developers {
            developer {
                id "hywan"
                name "Ivan Enderlin"
                url "https://github.com/Hywan"
            }
        }
    }

    publishing {
        publications {
            MyPublication(MavenPublication) {
                from components.java
                groupId "org.wasmer"
                artifactId "wasmer-jni-" + inferWasmerJarAppendix()
                version project.version

                artifacts {
                    archives jar
                }

                pom.withXml {
                    def root = asNode()
                    root.children().last() + pomConfig
                }
            }
        }
    }

    /// Second, set up Bintray.
    bintray {
        user = System.getenv("BINTRAY_USER")
        key = System.getenv("BINTRAY_API_KEY")
        publications = ["MyPublication"]
        pkg {
            repo = "wasmer-jni"
            name = "wasmer-jni"
            licenses = ["MIT"]
            vcsUrl = "https://github.com/wasmerio/wasmer-java.git"
            userOrg = "wasmer"
            desc = "Wasmer JNI is a library to execute WebAssembly binaries"
        }
    }
}

// Local Variables:
// mode: java
// End:
// vim: set ft=java :
